import requests
import sys
import os 

import os
import requests


def upload_file_with_auth(url, username, password, filename):
    # 创建一个会话对象
    session = requests.Session()

    # 设置认证信息
    session.auth = (username, password)

    dirname, filename_ = os.path.split(filename)

    # 获取文件大小
    file_size = os.path.getsize(filename)

    # 初始化已上传的字节数
    uploaded_bytes = 0

    # 打开文件
    with open(filename, 'rb') as file:
        while True:
            # 读取下一个 chunk
            chunk = file.read(81920)
            if not chunk:
                break

            # 发起上传请求
            response = session.post(url, files={'file': (filename_, chunk)})

            # 更新已上传的字节数
            uploaded_bytes += len(chunk)

            # 计算并打印上传进度（以百分比形式）
            progress = uploaded_bytes / file_size * 100
            print(f"上传进度：{progress:.2f}%")

    # 检查响应
    if response.status_code == 200:
        print('文件上传成功')
    else:
        print('文件上传失败%s' %response)


if __name__ == "__main__":
    # file_ = sys.argv[1]
    file_ = 'D:\\JSONData\\H_SCAN\\微信图片_20240104153206.jpg'
    # 示例用法
    upload_file_with_auth('http://127.0.0.1:5000/upload', 'sumz', 'Sumz', file_)